package graduation.project.store;

import graduation.project.body.Expression;
import graduation.project.body.Mutants;
import graduation.project.exception.NonExpressionException;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

public class FileMutants implements IMutants {

	public Mutants getMutants(String mutantsID) {
		Mutants mut = null;
		try {
			String originExID = mutantsID.substring(0, mutantsID.indexOf('_'));
			String faultType = mutantsID.replaceAll("[0-9]", "");
			File mutantsFile = new File("D:\\data\\" + originExID + "\\mutants\\" + mutantsID);
			BufferedReader in = new BufferedReader(new FileReader(mutantsFile));
			ArrayList<String> contents = new ArrayList<String>();
			
			String s;			
			while( (s = in.readLine()) != null)
					contents.add(s);
			
			ArrayList<Expression> mutants = new ArrayList<Expression>();
			String originEx = (String)contents.get(1);
			
			for(int i = 2; i < contents.size(); i++)
				mutants.add(new Expression((String)contents.get(i)));
			
			mut = new Mutants(originEx, mutantsID, faultType);
			mut.setMutants(mutants);
			in.close();
		} catch (FileNotFoundException e) {
			System.out.println("The file does not exist");
			e.printStackTrace();
		}catch(IOException e){
			System.out.println("Occurring error when read file");
			e.printStackTrace();
		}catch (NonExpressionException e){
			System.out.println("invalid expression");
			e.printStackTrace();
		}		
		
		return mut;
	}

	public int insertMutants(Mutants m) {
		int result = 0;
		try{
			if(m == null)
				return 0;
			String mutantsID = m.getMutantsID();
			String originEx = m.getOriginEx();
			String originExID = Integer.toString(originEx.hashCode());
			ArrayList<Expression> muts = m.getMutants();
			File dir = new File("D:\\data\\" + originExID + "\\mutants\\");
			dir.mkdirs();
			File mutantsFile = new File("D:\\data\\" + originExID + "\\mutants\\" + mutantsID);
			
			if( ! mutantsFile.createNewFile()){
				System.out.println("the file exists.");
				return 0;
			}
			
			PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(mutantsFile)));
			out.println(mutantsID);
			out.println(originEx);
			
			for(int i = 0; i < muts.size(); i++)
				out.println(muts.get(i).getExpression());
			
			result = 1;
			out.close();
		}catch(IOException e){
			System.out.println("occurring error when write the file.");
			e.printStackTrace();
		}
			
		return result;
	}

	public int modifyMutants(Mutants m) {
		// TODO Auto-generated method stub
		return 0;
	}

}
